<template>
  <div id="materRequirePlanDia">
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="需求计划详情"
      :visible.sync="inComData.materRequirePlanDiaStatus"
      :fullscreen="true"
      :modal="false"
      :destroy-on-close="true"
      class="addsiloScan"
      @closed="closededitDialogStatus"
      @open="openeditDialogStatus"
    >
      <div
        style="width: 70%"
        class="dialogItem"
      >
        <el-form
          :model="editForm.biDto"
          :rules="rules"
          ref="editForm"
          label-width="100px"
          style="width: 80%; margin: 0 auto"
        >
          <el-row class="titleInfo">基础信息</el-row>
          <el-row
            type="flex"
            justify="space-between"
            align="middle"
          >
            <el-col :span="7"
              ><el-form-item
                label="计划名称"
                prop="planName"
              >
                <el-input
                  v-model="editForm.biDto.planName"
                  placeholder="请输入"
                  disabled
                ></el-input> </el-form-item
            ></el-col>
            <el-col :span="9"
              ><el-form-item
                label="分部分项"
                prop="branchId"
                ><el-cascader
                  disabled
                  v-model="branchIdArr2"
                  style="width: 100%"
                  :options="branchItemOptions"
                  :props="{
                    expandTrigger: 'click',
                    value: 'id',
                    label: 'name',
                    children: 'itemList',
                  }"
                  @change="branchItemChange"
                ></el-cascader> </el-form-item
            ></el-col>
            <el-col :span="7"
              ><el-form-item
                label="计划日期"
                prop="planDate"
              >
                <el-date-picker
                  disabled
                  v-model="editForm.biDto.planDate"
                  style="width: 100%"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期"
                >
                </el-date-picker> </el-form-item
            ></el-col>
          </el-row>
          <el-row
            type="flex"
            justify="space-between"
            align="middle"
            ><el-col :span="7"
              ><el-form-item
                label="责任人"
                prop="principalId"
              >
                <el-select
                  disabled
                  v-model="editForm.biDto.principalId"
                  placeholder="请选择"
                  style="width: 100%"
                  @focus="getEnableUserListApi"
                >
                  <el-option
                    v-for="item in manOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select> </el-form-item
            ></el-col>
            <el-col
              :span="9"
              class="flexCenter"
            >
              <el-row
                type="flex"
                justify="center"
              >
                <el-form-item
                  label="里程号"
                  prop="mileageStartKm"
                >
                  <span
                    slot="label"
                    style="margin-left: 10px"
                    >里程号&nbsp;DK</span
                  >
                  <el-input
                    disabled
                    style="width: calc(100% + 20px)"
                    v-model="editForm.biDto.mileageStartKm"
                    type="number"
                    placeholder=""
                  ></el-input>
                </el-form-item>
                <el-form-item
                  class="nostar"
                  prop="mileageStartM"
                  label-width="40px"
                >
                  <span
                    slot="label"
                    style="margin-left: 10px"
                    >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;+</span
                  >
                  <el-input
                    disabled
                    style="width: calc(100% - 10px); margin-left: 10px"
                    type="number"
                    v-model="editForm.biDto.mileageStartM"
                    placeholder=""
                  ></el-input
                ></el-form-item>
                <el-form-item
                  class="nostar"
                  prop="mileageEndKm"
                  label-width="60px"
                  ><span slot="label">至DK</span
                  ><el-input
                    disabled
                    style="width: calc(100% + 10px)"
                    type="number"
                    v-model="editForm.biDto.mileageEndKm"
                    placeholder=""
                  ></el-input
                ></el-form-item>
                <el-form-item
                  class="nostar"
                  prop="mileageEndM"
                  label-width="40px"
                >
                  <span slot="label">+</span
                  ><el-input
                    disabled
                    style="width: 100%"
                    type="number"
                    v-model="editForm.biDto.mileageEndM"
                    placeholder=""
                  ></el-input
                ></el-form-item>
              </el-row>
            </el-col>
            <el-col :span="7"
              ><el-form-item label="备注">
                <el-input
                  :title="editForm.biDto.remark"
                  disabled
                  v-model="editForm.biDto.remark"
                ></el-input> </el-form-item
            ></el-col>
          </el-row>
          <el-row>
            <el-col :span="7">
              <el-form-item label="相关文件：">
                <div>
                  <p
                    class="fileInfos"
                    v-for="(f, index) in editForm.biDto.fileInfos"
                    @click="fileDetailHandler(f)"
                  >
                    <i
                      :class="
                        /\.(jpeg|jpg|gif|png|bmp)$/i.test(f.name)
                          ? 'el-icon-picture-outline'
                          : 'el-icon-document'
                      "
                    ></i>
                    {{ f.name }}
                  </p>
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row class="titleInfo">采购明细</el-row>
          <el-row>
            <el-form-item
              label-width="0"
              prop="requirementsPlanItems"
            >
              <el-table
                :data="editForm.biDto.requirementsPlanItems"
                border
                style="width: 100%; min-height: 300px"
                :header-cell-style="{ 'text-align': 'center' }"
                :cell-style="{ 'text-align': 'center' }"
              >
                <el-table-column
                  type="index"
                  label="序号"
                  width="55"
                />
                <el-table-column
                  label="物料名称"
                  prop="materialName"
                >
                </el-table-column>
                <el-table-column
                  label="规格型号"
                  prop="modelName"
                >
                </el-table-column>
                <el-table-column
                  label="单位"
                  prop="unit"
                >
                </el-table-column>
                <el-table-column
                  label="单价"
                  prop="unitPrice"
                >
                </el-table-column>
                <el-table-column
                  label="设计用量"
                  prop="designQuantity"
                >
                </el-table-column>
                <el-table-column
                  label="计划用量"
                  prop="planQuantity"
                >
                </el-table-column>
                <el-table-column
                  label="税后单价"
                  prop="taxUnitPrice"
                >
                </el-table-column>
                <el-table-column
                  label="税后总价"
                  prop="taxTotalPrice"
                >
                </el-table-column>
                <el-table-column
                  label="备注"
                  prop="remark"
                >
                  <template slot-scope="scope">
                    {{ scope.row.remark == '' ? '/' : scope.row.remark }}
                  </template>
                </el-table-column>
              </el-table></el-form-item
            >
          </el-row>
        </el-form>

        <el-row
          slot="footer"
          type="flex"
          justify="center"
        >
          <div>
            <el-button
              v-if="editForm.biDto.permission"
              type="warning"
              @click="auditHandler('detail', editForm.biDto)"
              >审核</el-button
            >
            <el-button @click="inComData.materRequirePlanDiaStatus = false"
              >返回</el-button
            >
          </div>
        </el-row>
      </div>
      <div
        style="width: calc(30% - 20px); height: 100%; margin-left: 20px"
        class="dialogItem"
      >
        <approxFlow
          ref="approxFlow"
          :steps="steps"
        ></approxFlow>
      </div>
    </el-dialog>
    <previewImg ref="previewImg"></previewImg>

    <toExamine
      ref="toExamine"
      :steps="steps"
      :approxForm="approxForm"
      :toExamineData="toExamineData"
    ></toExamine>
  </div>
</template>

<script>
import {
  getRequirePlanPage,
  getRequirePlanDetail,
  addRequirePlan,
  addRequireDraftPlan,
  updateRequirePlan,
  deleteRequirePlan,
  getRequirePlanExport,
  getBranchItemList,
  getEnableUserList,
  getMaterialTree,
  getMaterialTypeDetail,
  getMaterialDetail,
  uploadFile,
  uploadAnnexFile,
  deleteFile,
  downloadFile,
  terminatePlan,
  executeTaskPlan,
  getNextNodeAssignWay,
} from '/src/http/materialDispatch/materRequirePlan.js'
import { getProcessLog, deleteFileList } from '/src/http/commonApi.js'
import download from '/src/utils/downLoad.js'
import importData from '/src/component/assembly/importData.vue'
import approxFlow from '/src/component/assembly/approxFlow.vue'
import toExamine from '/src/component/assembly/toExamine.vue'
import previewImg from '/src/component/previewImg/previewImg.vue'

export default {
  components: {
    importData,
    approxFlow,
    toExamine,
    previewImg,
  },
  data() {
    return {
      ccListStatus: false,
      manOptions: [],
      ccList: [],

      toExamineData: {
        toExamineDataStatus: false,
        isSearch: false,
      },
      approxForm: {
        approveOperation: '1',

        opinion: '发起了审批',
      },
      steps: {},

      planName: '',
      planDate: '',
      branchIdArr: [],
      branchIdArr2: [],
      mileageStartKm: null,
      mileageStartM: null,
      mileageEndKm: null,
      mileageEndM: null,
      branchItemOptions: [],
      manOptions: [],
      materialOptions: [],

      startKm: null,
      startM: null,
      endKm: null,
      endM: null,
      dialogVisible: false,
      projectInput: '',
      renderData: [],
      renderDataThree: [],
      TreeData: [],
      total: 0,
      pageSize: 10,
      pageNum: 1,
      isSearch: false,

      isDraft: false,
      editTitle: '',
      isDetail: false,
      editForm: {
        assignees: [],
        opinion: '发起审核',
        biDto: {
          id: null,
          planName: '',
          branchId: null,
          branchItemId: null,
          planDate: '',
          files: [],
          fileIds: [],
          principalId: null,
          mileageStartKm: null,
          mileageStartM: null,
          mileageEndKm: null,
          mileageEndM: null,
          remark: '',
          requirementsPlanItems: [
            {
              typeOptions: [],
              materialId: null,
              modelId: null,
              unit: '',
              unitPrice: null,
              designQuantity: null,
              planQuantity: null,
              taxUnitPrice: null,
              taxTotalPrice: null,
              remark: '',
            },
          ],
        },
        ccList: [],
      },
      rules: {
        planName: [{ required: true }],
        branchId: [{ required: true }],
        branchItemId: [{ required: true }],
        planDate: [{ required: true }],
        principalId: [{ required: true }],
        mileageStartKm: [{ required: true }],
        mileageStartM: [{ required: true }],
        mileageEndKm: [{ required: true }],
        mileageEndM: [{ required: true }],
      },
      multipleSelection: [],
      multipleSelectionIds: [],
      deletemultiple: [],
      detailName: '',

      active: 0,
      uploadUrl: '',
      fileList: [],
      deleteArrIds: [],
      biId: '',
      percentage: 0,
      tableHeight: '0px',

      detailData: {},
    }
  },
  props: {
    inComData: Object,
  },
  mounted() {
    this.getBranchItemListApi()
    this.getEnableUserListApi()
    this.getMaterialTreeApi()
    this.getRequirePlanPageApi()
  },

  methods: {
    fileDetailHandler(item) {
      if (/\.(jpeg|jpg|gif|png|bmp)$/i.test(item.name)) {
        downloadFile({ path: item.path }).then((res) => {
          let url = URL.createObjectURL(res)

          this.$refs['previewImg'].showImg(url, item.name)
        })
      } else {
        downloadFile({ path: item.path }).then((res) => {
          download.stream(res, item.name)
        })
      }
    },
    closededitDialogStatus() {
      this.inComData.materRequirePlanDiaStatus = false
    },
    openeditDialogStatus() {
      this.seeDetail(this.inComData.data)
    },

    seeDetail(data) {
      this.fileList = []

      getRequirePlanDetail(data.id).then((res) => {
        if (res.code == 200) {
          this.editForm.biDto = res.data

          this.branchIdArr2 = [
            this.editForm.biDto.branchId,
            this.editForm.biDto.branchItemId,
          ]
          if (this.$refs['editForm']) {
            this.$refs['editForm'].resetFields()
          }
          this.editForm.biDto.fileIds = []
          this.editForm.biDto.fileInfos.forEach((item) => {
            this.editForm.biDto.fileIds.push(item.id)
            this.fileList.push({
              name: item.name,
              url: item.path,
              id: item.id,
            })
          })
          this.editForm.biDto.requirementsPlanItems.forEach((item) => {
            this.getMaterialTypeDetailApi(item)
          })

          if (this.$refs['editForm']) {
            this.$refs['editForm'].resetFields()
          }
        }
      })
      if (data.state !== 'draft') {
        getProcessLog({ id: data.orderId }).then((res) => {
          if (res.code == 200) {
            this.steps = res.data
            this.steps.state = this.editForm.biDto.state
          } else {
            this.$message.error(res.message)
          }
        })
      }
    },

    toExamineStatusChange() {
      this.importDataData.importDataStatus = true
    },

    toExamineFun() {
      if (Object.keys(this.detailData).length > 0) {
        this.startProcess(this.detailData)
      } else {
        this.startProcess(this.editForm.biDto)
      }
    },
    toExamineDataClean() {
      this.toExamineData = {
        toExamineDataStatus: false,
        isSearch: false,
      }
      this.approxForm = {
        approveOperation: '1',

        opinion: '',
      }
    },

    startProcess(biDto) {
      console.log('biDto::: ', biDto)
      let params = {
        state: biDto.state,
        type: 'mlRequirementsPlan',
      }
      if (this.approxForm.approveOperation === '0') {
        this.terminatePlanApi(biDto.id)
      } else if (this.approxForm.approveOperation === '1') {
        getNextNodeAssignWay(params).then((res) => {
          if (res.code == 200) {
            if (!res.data) {
              this.executeTaskPlanApi(0, biDto)
            } else if (res.data.assignWay === 0 || res.data.assignWay === 2) {
              if (biDto.state == 'draft' || !biDto.state) {
                let params = biDto
                if (params.fileInfos) {
                  if (params.fileInfos.length > 0) {
                    params.fileInfos.forEach((item) => {
                      params.fileIds.push(item.id)
                    })
                  }
                } else {
                  if (this.fileList.length > 0) {
                    params.fileIds = []
                  }
                }

                this.addRequirePlanApi(params)
              } else {
                this.executeTaskPlanApi(0, biDto)
              }
            } else if (res.data.assignWay === 1) {
            }
          } else {
            this.$message.error(res.message)
          }
        })
      }
    },

    ccListSumbit() {
      this.startProcess(this.editForm.biDto)
    },

    auditHandler(name = '', data) {
      if (name === 'detail') {
        this.detailName = 'detail'
        this.$confirm(`确认要审核【${data.planName}】？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            this.approxForm.opinion = ''

            getProcessLog({ id: data.orderId }).then((res) => {
              if (res.code == 200) {
                this.toExamineData.toExamineDataStatus = true
                this.steps = res.data
              } else {
                this.$message.error(res.message)
              }
            })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消审批',
            })
          })
      } else {
        this.detailName = ''
        if (this.multipleSelection.length > 1) {
          this.$message({
            message: '审批不能选择多条',
            type: 'warning',
          })
          this.multipleSelection = []
        } else if (this.multipleSelection.length == 0) {
          this.$message({
            message: '未选择需求计划',
            type: 'warning',
          })
        } else if (this.multipleSelection[0].state === 'draft') {
          this.$message.warning('该需求计划为草稿，不能进行审批')
        } else if (!this.multipleSelection[0].permission) {
          if (this.multipleSelection[0].state === 'completed') {
            this.$message.warning('该需求计划已完成审批')
          } else if (this.multipleSelection[0].state === 'terminated') {
            this.$message.warning('该需求计划已结束审批')
          } else {
            this.$message.warning('无审批权限')
          }
        } else {
          this.$confirm(
            `确认要审核选中的【${this.multipleSelection[0].planName}】？`,
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }
          )
            .then(() => {
              this.approxForm.opinion = ''

              getProcessLog({ id: this.multipleSelection[0].orderId }).then(
                (res) => {
                  if (res.code == 200) {
                    this.toExamineData.toExamineDataStatus = true
                    this.steps = res.data
                  } else {
                    this.$message.error(res.message)
                  }
                }
              )
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消审批',
              })
            })
        }
      }
    },

    branchItemChange(v) {
      this.editForm.biDto.branchId = v[0]
      this.editForm.biDto.branchItemId = v[1]
    },

    materialChange(v, row) {
      row.modelId = null
      this.getMaterialDetailApi(v[v.length - 1], row)
    },

    getUnitHandler(val, item) {
      item.typeOptions.forEach((el) => {
        if (el.id == val) {
          item.unit = el.unit
        }
      })
    },

    /**
     * 接口
     *  */

    getBranchItemListApi(pageNum = 1, pageSize = 999) {
      let params = {
        pageNum,
        pageSize,
      }
      getBranchItemList(params).then((res) => {
        if (res.code == 200) {
          this.branchItemOptions = res.data.records
        }
      })
    },

    getEnableUserListApi() {
      getEnableUserList().then((res) => {
        if (res.code == 200) {
          this.manOptions = res.data
        }
      })
    },

    getMaterialTreeApi() {
      getMaterialTree().then((res) => {
        if (res.code == 200) {
          this.materialOptions = res.data
        }
      })
    },

    async getMaterialTypeDetailApi(item) {
      getMaterialTypeDetail(item.materialId).then(async (res) => {
        if (res.code == 200) {
          await this.getMaterialDetailApi(res.data.id, item)
          if (res.data.parentIds == null) {
            await this.a([res.data.pid, item.materialId], res.data.id, item)
          } else {
            await this.a(res.data.parentIds, res.data.id, item)
          }
        }
      })
    },
    async a(str, id, item) {
      await this.getMaterialTreeApi()

      if (str instanceof Array) {
        item.materialId = str
      } else {
        item.materialId = str.split(',').map(Number)
        item.materialId.shift()
        item.materialId.push(id)
      }
    },

    async getMaterialDetailApi(id, row) {
      await getMaterialDetail(id).then((res) => {
        if (res.code == 200) {
          this.$set(row, 'typeOptions', res.data)
        }
      })
    },

    getRequirePlanPageApi(
      pageNum = 1,
      pageSize = 10,
      planName = '',
      branchId = null,
      branchItemId = null,
      planDate = [],
      mileageStartKm = null,
      mileageStartM = null,
      mileageEndKm = null,
      mileageEndM = null
    ) {
      let params = {}
      if (planDate.length == 0) {
        params = {
          pageNum,
          pageSize,
          planName,
          branchId,
          branchItemId,
          planDate,
          mileageStartKm,
          mileageStartM,
          mileageEndKm,
          mileageEndM,
        }
      } else {
        if (planDate[0] === planDate[1]) {
          params = {
            pageNum,
            pageSize,
            planName,
            branchId,
            branchItemId,
            planDate: planDate[0],
            mileageStartKm,
            mileageStartM,
            mileageEndKm,
            mileageEndM,
          }
        } else {
          params = {
            pageNum,
            pageSize,
            planName,
            branchId,
            branchItemId,
            planStartDate: planDate[0],
            planEndDate: planDate[1],
            mileageStartKm,
            mileageStartM,
            mileageEndKm,
            mileageEndM,
          }
        }
      }
      getRequirePlanPage(params).then((res) => {
        if (res.code == 200) {
          this.renderData = res.data.records
          this.total = res.data.total
        }
      })
    },

    getRequirePlanDetailApi(data) {
      this.fileList = []

      getRequirePlanDetail(data.id).then((res) => {
        if (res.code == 200) {
          this.editForm.biDto = res.data

          this.branchIdArr2 = [
            this.editForm.biDto.branchId,
            this.editForm.biDto.branchItemId,
          ]
          if (this.$refs['editForm']) {
            this.$refs['editForm'].resetFields()
          }
          this.editForm.biDto.fileIds = []
          this.editForm.biDto.fileInfos.forEach((item) => {
            this.editForm.biDto.fileIds.push(item.id)
            this.fileList.push({
              name: item.name,
              url: item.path,
              id: item.id,
            })
          })
          this.editForm.biDto.requirementsPlanItems.forEach((item) => {
            this.getMaterialTypeDetailApi(item)
          })

          if (this.$refs['editForm']) {
            this.$refs['editForm'].resetFields()
          }
        }
      })
      if (data.state !== 'draft') {
        getProcessLog({ id: data.orderId }).then((res) => {
          if (res.code == 200) {
            this.steps = res.data
            this.steps.state = this.editForm.biDto.state
          } else {
            this.$message.error(res.message)
          }
        })
      }
    },

    getNextNodeAssignWayApi(state = '', type = 'mlRequirementsPlan') {
      let params = {
        state,
        type,
      }
      getNextNodeAssignWay(params).then((res) => {
        if (res.code == 200) {
          this.editForm.assignees = res.data.assignees
          this.editForm.ccList = res.data.ccList
        } else {
          this.$message.error(res.message)
        }
      })
    },

    terminatePlanApi(id) {
      terminatePlan(id).then((res) => {
        if (res.code == 200) {
          this.$message.success('终止成功')
          this.toExamineData.toExamineDataStatus = false
          this.inComData.materRequirePlanDiaStatus = false
          this.detailData = {}
          this.$parent.workbenchTaskCountyApi()
          this.$parent.shuaxin()
        } else {
          this.$message.error(res.message)
        }
      })
    },

    executeTaskPlanApi(type, biDto) {
      if (type == 0) {
        let params = {
          assignees: [],
          opinion: this.approxForm.opinion,
          ccList: this.ccList,
          biDto,
        }
        params.biDto.requirementsPlanItems.forEach((a) => {
          if (a.materialId instanceof Array) {
            a.materialId = a.materialId[a.materialId.length - 1]
          }
        })
        executeTaskPlan(params).then((res) => {
          if (res.code == 200) {
            this.$message.success('审批成功')

            this.toExamineData.toExamineDataStatus = false
            this.inComData.materRequirePlanDiaStatus = false

            this.detailData = {}
            this.$parent.workbenchTaskCountyApi()
            this.$parent.shuaxin()
          } else {
            this.$message.error(res.message)
            this.detailData = {}
          }
        })
      } else {
        this.toExamineData.toExamineDataStatus = false
        this.inComData.materRequirePlanDiaStatus = false
        this.terminatePlanApi(biDto.id)
      }
    },
    toExamineDataClean() {
      this.toExamineData = {
        toExamineDataStatus: false,
        isSearch: false,
      }
      this.approxForm = {
        approveOperation: '1',

        opinion: '',
      }
    },
  },
}
</script>

<style lang="less" scoped>
#warehouseReceipt {
  width: 100%;
  margin: 0 auto;
}
:deep(.el-dialog__header) {
  background-color: rgb(43, 43, 53);
}
:deep(.el-dialog__title) {
  color: #fff;
}

.flexCenter {
  display: flex;
  align-items: center;
}
.text-r {
  text-align: right;
}
.titleInfo {
  color: #409eff;
  margin-bottom: 10px;
}

:deep(.nostar .el-form-item__label:before) {
  display: none !important;
}
.noFile {
  color: #d6d6d6;
  font-size: 12px;
}
.haveFile {
  color: #519fec;
  cursor: pointer;
}
.haveFile:hover {
  color: #0080ff;
}
.dialogItem {
  float: left;
}
.circleSpan::before {
  content: '';
  display: inline-block;
  width: 0px;
  height: 0px;
  border: 5px solid;
  border-radius: 50%;
  margin-right: 5px;
}
:deep(.el-input.is-disabled .el-input__inner) {
  color: #606266;
  background-color: #fcfcfc;
}
:deep(.el-textarea.is-disabled .el-textarea__inner) {
  color: #606266;
  background-color: #fcfcfc;
}

:deep(.el-upload-list__item .el-icon-close-tip) {
  display: none !important;
}
.fileInfos:hover {
  color: #409eff;
  cursor: pointer;
}
</style>
